package com.juzhencms.apps.busi.web;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.juzhencms.apps.busi.service.DictionaryService;
import com.juzhencms.apps.busi.service.OrganizationService;
import com.juzhencms.apps.busi.service.UserService;
import com.juzhencms.apps.base.common.database.DBTable;
import com.juzhencms.apps.base.common.util.StringUtil;
import com.juzhencms.apps.base.common.util.WebUtil;


@Controller
@RequestMapping("/organization")
public class OrganizationController  extends BaseController{
	
	@Autowired
	private DictionaryService dictionaryService;
	
	@Autowired
	private UserService userService;
	
	@Autowired
	private OrganizationService organizationService;
	
	//机构列表
	@RequestMapping(value="/gridlistData",produces="text/html; charset=UTF-8")
	@ResponseBody
	public String gridlistData(HttpServletRequest request){
		
		Map data=new HashMap();
		//查询列表数据
		//List dataList = organizationService.getLists("id,name,parent_id as parentId,position,is_sys,publish,create_time ", " del_flag=0 and id in("+this.getLoginUser().getSubOrgIds()+") ", null, null, 0, 0,0);
		//查询当前机构并设置为不可编辑
		List dataList=this.getCommonService().getJdbcDao().querySql("select id,name,parent_id as parentId,position,1 as is_sys,publish,create_time from "+DBTable.organization+" where del_flag=0 and id=?",new Object[] {this.getLoginUser().getOrgId()});
		//改进方案，查询当前机构及下属所有机构
		String tmpOrgIds=""+this.getLoginUser().getOrgId();
		while(!tmpOrgIds.equals("")) {
			
			List tmpList=this.getCommonService().getJdbcDao().querySql("select id,name,parent_id as parentId,position,is_sys,publish,create_time from "+DBTable.organization+" where del_flag=0 and parent_id in ("+tmpOrgIds+")");
			tmpOrgIds="";
			if(tmpList!=null) {
				for(int i=0;i<tmpList.size();i++) {
					Map tmpRow=(Map)tmpList.get(i);
					dataList.add(tmpRow);
					if(i==0) {
						tmpOrgIds+=tmpRow.get("id").toString();
					}else {
						tmpOrgIds+=","+tmpRow.get("id").toString();
					}
				}
			}
		}
		
		
		if(dataList!=null && dataList.size()>0){
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			for(int i=0;i<dataList.size();i++){
				Map row=(Map)dataList.get(i);
				Date date = (Date)row.get("create_time");
				row.put("create_time",sdf.format(date));
				
				//判断是否有上级权限，没有权限则将parentId置为0
				int parentId = new Integer(row.get("parentId").toString());
				if( parentId > 0) {
					if(!organizationService.isAuth(parentId)) {
						row.put("parentId", 0);
					}
				}
			}
		}
		data.put("data", dataList.toArray());
		return WebUtil.resultString(data,request);
	}
	
	//详情
	@RequestMapping(value="/detailData/{id}",produces="text/html; charset=UTF-8")
	@ResponseBody
	public String detailData(@PathVariable("id") String id,HttpServletRequest request){
		Map data=new HashMap();
//		Map record=this.getCommonService().getJdbcDao().queryRow("select * from "+DBTable.organization+" where id=?",new Object[]{id});	
		String where = " del_flag=0 and id = ? ";	
		List whereParamList = new ArrayList();
		int getId = new Integer(id);
		whereParamList.add(getId);
		Map record = organizationService.getDetail("", where, whereParamList, "",0);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date date = (Date) (record.get("create_time")==null?"":record.get("create_time"));
		record.put("create_time",sdf.format(date) );
		data.put("data", record);
		return WebUtil.resultString(data,request);
	}
	
	//新增/保存
	@RequestMapping(value="/save",produces="text/html; charset=UTF-8")
	@ResponseBody
	public String save(HttpServletRequest request){
		Map data = JSON.parseObject(request.getParameter("data"), Map.class); 
		data.put("del_flag", 0);
		String id=null;
		if(data.get("id")!=null){
			id=data.get("id").toString();
		}
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date date = new Date();
		int intcurretnOrgid=0;
		
		//非root权限的管理员用户添加机构信息时，上级机构必选
		if(!this.isRootUser() &&  StringUtil.isNullOrEmpty(data.get("parent_id")) ) {
			Map result=new HashMap();
			result.put("result", 0);
			result.put("msg", "请选择上级机构");
			return WebUtil.resultString(result,request);
		}
		
		if(id==null || id.equals("")){
			if(data.get("create_time")==null || data.get("create_time").equals("")){
				data.put("create_time", sdf.format(date));
			}
			Map prevOrg=this.getCommonService().getJdbcDao().queryRow("select position from "+DBTable.organization+" where del_flag=0 and parent_id=? order by position desc limit 1",new Object[]{data.get("parent_id").toString()});	
			int position = 0;
			if(prevOrg!=null) {
				 position = Integer.parseInt(prevOrg.get("position").toString());
			}
			data.put("position", position+1);
			data.put("create_user", this.getLoginUserId());
			intcurretnOrgid=this.getCommonService().getJdbcDao().addObj(DBTable.organization, data);
		}else{
			intcurretnOrgid=Integer.parseInt(data.get("id").toString());
			data.put("update_time", sdf.format(date));
			data.put("update_user", this.getLoginUserId());
			this.getCommonService().getJdbcDao().updateObj(DBTable.organization, data, "id");
		}
		Map result=new HashMap();
		result.put("result", 1);
		result.put("msg", "保存成功");
		
		return WebUtil.resultString(result,request);
		
	}
	
	//选择上级机构分类树（不可选择本身）
	@SuppressWarnings("all")
	@RequestMapping(value="/getParentTreeOrgList/{id}",produces="text/html; charset=UTF-8")
	@ResponseBody
	public String getParentTreeOrgList(@PathVariable("id") String id,HttpServletRequest request){
		if(id==null || "".equals(id) || "undefined".equals(id)) {
			id="0";
		}
//		Map parentIdMap = this.getCommonService().getJdbcDao().queryRow(" select parent_id from "+ DBTable.organization + " where id = ? ",new Object[]{id});
		List dataList=this.getEditParentOrgTree(new Integer(id), 0);
		Map data=new HashMap();
		data.put("data", dataList);
		return WebUtil.resultString(data,request);
	}
	
	//获取可编辑机构树，应用机构表单中
	@SuppressWarnings("all")
	private List getEditParentOrgTree(int id,int pid){
		//
		String orgCondition = "";
		List dataList=this.getCommonService().getJdbcDao().querySql("select id,name,parent_id from "+DBTable.organization+" where parent_id=? and del_flag = 0 "+orgCondition+" order by position asc,id asc",new Object[]{pid});
		for(int i=0;i<dataList.size();i++){
			Map Org=(Map)dataList.get(i);
			
			//默认展开根节点
			if(Org.get("parent_id").toString().equals("0")) {
				Org.put("open",true);
			}
			
			//不在登录用户权限内的机构不可选择
			int current_org_id = new Integer(Org.get("id").toString());
			if(!organizationService.isAuth(current_org_id)) {
				Org.put("chkDisabled",true);
			}
			
			//本机构与子机构处理
			if(Org.get("id").toString().equals(""+id)){
				//本机构不能选择并且不再查询子机构
				Org.put("chkDisabled",true);
				//System.out.println(id);
			}else{
				List subList=this.getEditParentOrgTree(id, current_org_id);
				if(subList!=null && subList.size()>0){
					Org.put("children", subList);
				}
			}
			
			//特殊情况，如果当前编辑的是用户所属机构，则上级机构要允许选择，这种情况下只能选择上级机构这一个节点
			if(id==this.getLoginUser().getOrgId() && Org.get("id").toString().equals(this.getLoginUser().getOrgParentId())){
				Org.put("chkDisabled",null);
			}
			
		}
		return dataList;
	}	
	
	//获取机构分类树,应用场景：机构外表单外组件使用
	@RequestMapping(value="/getOrgTreeData",produces="text/html; charset=UTF-8")
	@ResponseBody
	public String getOrgTreeData(HttpServletRequest request){
		//条件
		String whereStr = " ";
		List dataList = organizationService.getOrgTree(this.getLoginUser().getOrgId());
		Map data = new HashMap();
		data.put("data",dataList);
		return WebUtil.resultString(data,request);
	}
	
	//获取机构分类树及下级角色，用于审批中的会签功能，为公共权限
	@RequestMapping(value="/getOrgRoleTreeData",produces="text/html; charset=UTF-8")
	@ResponseBody
	public String getOrgRoleTreeData(HttpServletRequest request){
		//接收当前审批记录ID
		String checkRecordId=request.getParameter("checkRecordId");
		if(checkRecordId==null || checkRecordId.equals("")) {
			Map result=new HashMap();
			result.put("result",0);
			result.put("msg", "参数有误");
			return WebUtil.resultString(result,request);
		}
		
		
		Map checkRecord=this.getCommonService().getJdbcDao().queryRow("select * from "+DBTable.checkRecord+" where id=? ", new Object[] {checkRecordId});
		
		if(checkRecord==null) {
			Map result=new HashMap();
			result.put("result",0);
			result.put("msg", "参数有误");
			return WebUtil.resultString(result,request);
		}
		//获取当前审批角色ID,查询角色数据时不需要包含当前角色，因为生成会签流程时会自动包含
		int checkRoleId=Integer.parseInt(checkRecord.get("check_role_id").toString());
		
		List treeNodeList=new ArrayList();
		
		List orgList = organizationService.getOrgTree(this.getLoginUser().getOrgId());
		if(orgList!=null) {
			List orgIdList=new ArrayList();
			for(int i=0;i<orgList.size();i++) {
				Map tmpOrg=(Map)orgList.get(i);
				orgIdList.add(tmpOrg.get("id"));
				tmpOrg.put("id", "o"+tmpOrg.get("id"));
				tmpOrg.put("pId", "o"+tmpOrg.get("pId"));
				tmpOrg.put("chkDisabled", true);
				//第一个节点（当前机构）设置展开
				if(i==0) {
					tmpOrg.put("open", true);
				}else {
					tmpOrg.put("open", false);
				}
				
				
			}
			
			if(orgIdList.size()>0) {
				List roleList=this.getCommonService().getJdbcDao().querySql("select id,org_id as parent_id,name from "+DBTable.role+" where del_flag=0 and publish=1 and org_id in("+org.apache.commons.lang3.StringUtils.join(orgIdList, ",")+") and id!=? order by id asc limit 0,1000",new Object[] {checkRoleId});
				if(roleList!=null) {
					for(int i=0;i<roleList.size();i++) {
						Map tmpRole=(Map)roleList.get(i);
						tmpRole.put("pId", "o"+tmpRole.get("parent_id"));
						tmpRole.put("icon", "assets/global/plugins/jquery.ztree/img/diy/2.png");
						
					}
				}
				
				treeNodeList.addAll(roleList);
				treeNodeList.addAll(orgList);
			}
			
			
			
		}
		Map data = new HashMap();
		data.put("result", 1);
		data.put("data",treeNodeList);
		return WebUtil.resultString(data,request);
	}
	
	//更新排序位
	@RequestMapping(value="/updatePosition",produces="text/html; charset=UTF-8")
	@ResponseBody
	public String updatePosition(HttpServletRequest request){
		if(request.getParameter("position")==null || request.getParameter("id")=="")
			return "";
		this.getCommonService().getJdbcDao().updateSql("update "+DBTable.organization+" set position=? where id=?",new Object[]{request.getParameter("position"),request.getParameter("id")});
		Map result=new HashMap();
		result.put("result",1);
		result.put("msg", "操作成功");
		return WebUtil.resultString(result,request);
	}

	
	//删除
	@RequestMapping(value="/delete",produces="text/html; charset=UTF-8")
	@ResponseBody
	public String delete(HttpServletRequest request){
		Map data = JSON.parseObject(request.getParameter("data"), Map.class); 
		Map result=new HashMap();
		
		//
		String id=null;
		if(data.get("id")!=null){
			id=data.get("id").toString();
		}
		if(id==null || id.equals("")){
			result.put("result",0);
			result.put("msg", "操作失败，参数有误");
			return WebUtil.resultString(result,request);
		}else{	

			//是否存在子机构，存在不可删除
			String where = " del_flag=0 and parent_id = ? ";	
			List whereParamList = new ArrayList();
			int parentId = new Integer(id);
			whereParamList.add(parentId);
			Map getSonOrg = organizationService.getDetail("id", where, whereParamList, null, 0);
			if(getSonOrg==null) {
				this.getCommonService().getJdbcDao().updateSql("update "+DBTable.organization+" set del_flag=1,update_time=NOW() where id="+parentId);
			} else {
				result.put("result",0);
				result.put("msg", "操作失败，该机构下有子机构不可删除");
				return WebUtil.resultString(result,request);
			}
		}
		result.put("result",1);
		result.put("msg", "操作成功");
		return WebUtil.resultString(result,request);
	}
	
}
